var $ = function(id) {
    return document.getElementById(id);
}

var firstNamePattern    = "(^[a-zA-Z]{1,14}$)";
var lastNamePattern     = "(^[a-zA-Z]{1,14}$)";
var emailAddressPattern = "^[\\w\\.-]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$";
var userNamePattern     = "^[a-zA-Z0-9_-]{3,15}$"; // TODO: for dev purposes, username req. are simple
var password            = "^[a-zA-Z0-9_-]{3,15}$"; // TODO: for dev purposes, username req. are simple

var validationTargets = ["firstName|validation_firstName|Required field, upto 14 characters|" + firstNamePattern
                         , "lastName|validation_lastName|Required field, upto 14 characters|" + lastNamePattern
                         , "emailAddress|validation_emailAddress|Required, must be a valid email address|" + emailAddressPattern
                         , "userName|validation_userName|Required, must be between 3-15 characters|" + userNamePattern
                         , "password1|validation_password1|Required, must be between 3-15 characters|" + password
                         , "password2|validation_password2|Required, confirms previous password entry|" + password
                        ];


var inputValidator = function(validationTarget){
        var targetData = validationTarget.split("|");
        if ($(targetData[1]) && $(targetData[1]).firstChild != true){
            var textNode = document.createTextNode("");
            $(targetData[1]).appendChild(textNode);
        }

        if ($(targetData[0])) {
            var inputText = $(targetData[0]).value;
            var pattern = new RegExp(targetData[3]);
            if (pattern.test(inputText)){
                $(targetData[1]).firstChild.nodeValue = "";
            } else {
                $(targetData[1]).firstChild.nodeValue = targetData[2];
            }
        }
}

var initValidator = function(validationTargets){
    for (var index in validationTargets){
        inputValidator(validationTargets[index]);
    }
}

var onInputEvent = function(event){
    for (var index in validationTargets){
        var targetData = validationTargets[index].split("|");
        if (targetData[0] === event.target.id){
            inputValidator(validationTargets[index]);
            break;
        }
    }
}

var setupValiationHandlers = function(){

    initValidator(validationTargets);

    for (var index in validationTargets){
        var targetData = (validationTargets[index]).split("|");
        if ($(targetData[0])) {
            jsLib.event.add($(targetData[0]), "keyup", onInputEvent);
        }
    }
}

jsLib.dom.ready(setupValiationHandlers);
